/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nhncorp.neptune.common;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.http.SocketListener;
import org.mortbay.jetty.servlet.WebApplicationContext;

/**
 * Neptune의 Web 인터페이스를 위한 Http 서버
 */
public class NStatusHttpServer {
  private org.mortbay.jetty.Server webServer;
  private SocketListener listener;
  private WebApplicationContext webAppContext;
  private static final Log LOG =
    LogFactory.getLog(NStatusHttpServer.class.getName());

  private int port;
  /**
   * Create a status server on the given port.
   * The jsp scripts are taken from src/webapps/<name>.
   * @param name The name of the server
   * @param port The port to use on the server
   * @param findPort whether the server should start at the given port and 
   *        increment by 1 until it finds a free port.
   */
  public NStatusHttpServer(String name, String bindAddress, int port) throws IOException {
    String appDir = null;
    try {
      appDir = getWebAppsPath();
    } catch (IOException e) {
      LOG.warn("Web Monitor disabled cause: " + e.getMessage());
      return;
    }
    this.port = port;
    webServer = new org.mortbay.jetty.Server();
    listener = new SocketListener();
    listener.setPort(port);
    listener.setHost(bindAddress);
    webServer.addListener(listener);

    webAppContext = 
      webServer.addWebApplication("/", appDir + "/" + name);
  }

  /**
   * Set a value in the webapp context. These values are available to the jsp
   * pages as "application.getAttribute(name)".
   * @param name The name of the attribute
   * @param value The value of the attribute
   */
  public void setAttribute(String name, Object value) {
    webAppContext.setAttribute(name, value);
  }

  /**
   * Add a servlet in the server.
   * @param name The name of the servlet (can be passed as null)
   * @param pathSpec The path spec for the servlet
   * @param servletClass The servlet class
   */
  public <T extends HttpServlet> 
   void addServlet(String name, String pathSpec, 
                   Class<T> servletClass) {
   
    WebApplicationContext context = webAppContext;
    try {
      if (name == null) {
        context.addServlet(pathSpec, servletClass.getName());
      } else {
        context.addServlet(name, pathSpec, servletClass.getName());
      } 
    } catch (ClassNotFoundException ex) {
      throw makeRuntimeException("Problem instantiating class", ex);
    } catch (InstantiationException ex) {
      throw makeRuntimeException("Problem instantiating class", ex);
    } catch (IllegalAccessException ex) {
      throw makeRuntimeException("Problem instantiating class", ex);
    }
  }

  private static RuntimeException makeRuntimeException(String msg, 
                                                       Throwable cause) {
    RuntimeException result = new RuntimeException(msg);
    if (cause != null) {
      result.initCause(cause);
    }
    return result;
  }

  /**
   * Get the value in the webapp context.
   * @param name The name of the attribute
   * @return The value of the attribute
   */
  public Object getAttribute(String name) {
    return webAppContext.getAttribute(name);
  }

  /**
   * Get the pathname to the webapps files.
   * @return the pathname as a URL
   */
  private static String getWebAppsPath() throws IOException {
    URL url = NStatusHttpServer.class.getClassLoader().getResource("webapps");
    if (url == null) 
      throw new IOException("webapps not found in CLASSPATH");
    
    LOG.info("webapps: " + url.toString());
    return url.toString();
  }

  /**
   * Get the port that the server is on
   * @return the port
   */
  public int getPort() {
    return listener.getPort();
  }

  public void setThreads(int min, int max) {
    listener.setMinThreads(min);
    listener.setMaxThreads(max);
  }
  /**
   * Start the server. Does not wait for the server to start.
   */
  public void start() throws IOException {
    if(webServer == null) {
      return;
    }
    try {
      webServer.start();
    } catch (IOException ie) {
      LOG.error(ie);
      throw ie;
    } catch (Exception e) {
      IOException ie = new IOException("Problem starting http server");
      ie.initCause(e);
      throw ie;
    }
    LOG.info("Web-server up at: " + port);
  }

  /**
   * stop the server
   */
  public void stop() throws InterruptedException {
    if(webServer == null) {
      return;
    }

    webServer.stop();
  }

  /**
   * A very simple servlet to serve up a text representation of the current
   * stack traces. It both returns the stacks to the caller and logs them.
   * Currently the stack traces are done sequentially rather than exactly the
   * same data.
   */
//  public static class StackServlet extends HttpServlet {
//
//    private static final long serialVersionUID = -6284183679759467039L;
//
//    @Override
//    public void doGet(HttpServletRequest request, HttpServletResponse response)
//      throws ServletException, IOException {
//      
//      OutputStream outStream = response.getOutputStream();
//      ReflectionUtils.printThreadInfo(new PrintWriter(outStream), "");
//      outStream.close();
//      ReflectionUtils.logThreadInfo(LOG, "jsp requested", 1);      
//    }
//  }
}

